package cn.tedu.sp02.item.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItem(@PathVariable String orderId) throws InterruptedException {
        List<Item> items = itemService.getItem(orderId);

        //随机延迟代码
        if (Math.random() < 0.9){ //90%概率执行延迟代码
            //随机延迟时长
            int time = new Random().nextInt(2000);
            log.info("延迟： "+time);
            Thread.sleep(time);
        }
        return JsonResult.build().code(200).data(items);
    }

    //@RequestBody 完整的接受post请求协议体数据  前端传过来的分为协议头与协议体，get请求只接受协议头
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> list){
        itemService.decreaseNumbers(list);
        return JsonResult.build().code(200).msg("减少库存成功！");
    }

    @GetMapping("/favicon.ico")
    public void ico(){

    }
}
